<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="登录账号" prop="account">
        <el-input
          v-model="queryParams.account"
          placeholder="请输入登录账号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:merchant:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:merchant:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:merchant:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="Download"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['business:merchant:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="merchantList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="登录账号" align="center" prop="account" />
      <el-table-column label="商户等级" align="center" prop="merchantLevelName" />
      <el-table-column label="所属经销商" align="center" prop="dealer" />
      <el-table-column label="手机号" align="center" prop="phone" />

<!--
      <el-table-column label="信用额度" align="center" prop="creditLimit">
        <template #default="scope">
          <a style="cursor: pointer; color: #00ff00; margin-right: 10px" @click="handleCreditLimitRecord(scope.row)" title="点击查看明细">
            {{ scope.row.creditLimit}}
          </a>
        </template>
      </el-table-column>
-->
      <el-table-column label="余额" align="center" prop="balance">
        <template #default="scope">
          <a style="cursor: pointer; color: #20a0ff; margin-right: 10px" @click="handleBalanceRecord(scope.row)" title="点击查看明细">
            {{ scope.row.balance}}
          </a>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="帐号状态" width="80">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
<!--      <el-table-column label="创建时间" align="center" prop="createTime" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.createTime) }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->


      <el-table-column label="操作" >
        <template #default="scope">
          <el-divider direction="vertical"></el-divider>
          <el-dropdown >
              <span class="el-dropdown-link">更多
                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
            <template #dropdown>
              <el-dropdown-menu>
<!--                <el-dropdown-item>-->
<!--                  <a style="cursor: pointer; margin-right: 10px" @click="addCreditLimit(scope.row)">新增额度</a>-->
<!--                </el-dropdown-item>-->
                <el-dropdown-item>
                  <a style="cursor: pointer; margin-right: 10px" @click="addBalance(scope.row)">充值</a>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.status === '0'">
                  <a style="cursor: pointer; margin-right: 10px" @click="handleOperate(scope.row, 'close')">禁用</a>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.status === '1'">
                  <a style="cursor: pointer; margin-right: 10px" @click="handleOperate(scope.row, 'open')">启用</a>
                </el-dropdown-item>
                <el-dropdown-item>
                  <a style="cursor: pointer; margin-right: 10px" @click="handleUpdate(scope.row)" v-hasPermi="['business:merchant:edit']">修改</a>
                </el-dropdown-item>
                <el-dropdown-item>
                  <a style="cursor: pointer; margin-right: 10px" @click="handleDelete(scope.row)" v-hasPermi="['business:merchant:remove']">删除</a>
                </el-dropdown-item>
                <el-dropdown-item>
                  <a style="cursor: pointer; margin-right: 10px" @click="handleOperate(scope.row, 'restorePassWord')" >默认密码</a>
                </el-dropdown-item>

              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商户信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="merchantRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="登录账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入登录账号"  :disabled="isEdit"/>
        </el-form-item>

        <el-form-item label="商户等级" prop="merchantLevelName">
          <template #default="scope">
            <el-select v-model="form.merchantLevelName" size="small" style="width: 500px; margin-right: 10px" filterable clearable @change="merchantLevelChange(form.merchantLevelName)">
              <el-option v-for="item in merchantLevelArr" :key="item.name" :label="item.name" :value="item.name" />
            </el-select>
          </template>
        </el-form-item>

        <el-form-item label="经销商" prop="dealer">
          <el-input v-model="form.dealer" placeholder="请输入所属经销商" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
<!--        <el-form-item label="登录密码" prop="password">-->
<!--          <el-input v-model="form.password" placeholder="请输入登录密码" />-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>



    <el-dialog :title="title" v-model="merchantCreditLimitOpen" width="900px" append-to-body>
      <el-table v-loading="merchantCreditLimitLoading" :data="merchantCreditLimitList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商户" align="center" prop="merchantName" />
        <el-table-column label="订单单号" align="center" prop="orderNumber" />
        <el-table-column label="类型" align="center" prop="type">
          <template #default="scope">
            <span v-if="scope.row.type === 'in'">充值</span>
            <span v-if="scope.row.type === 'out'">支付</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="amount" />
        <el-table-column label="操作人" align="center" prop="createBy" />
        <el-table-column label="操作时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :title="title" v-model="merchantBalanceOpen" width="900px" append-to-body>
      <el-table v-loading="merchantBalanceLoading" :data="merchantBalanceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商户" align="center" prop="merchantName" />
        <el-table-column label="订单单号" align="center" prop="orderNumber" />
        <el-table-column label="类型" align="center" prop="type">
          <template #default="scope">
            <span v-if="scope.row.type === 'in'">客户充值</span>
            <span v-if="scope.row.type === 'out'">订单支付</span>
            <span v-if="scope.row.type === 'freightOut'">运费支付</span>
            <span v-if="scope.row.type === 'backIn'">订单退款</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="amount" />

        <el-table-column label="图片" align="center" prop="img">
          <template #default="scope">
            <img style="width: 50px; height: 50px;" :key="scope.row.id" :src="scope.row.img" alt="图片" v-if="scope.row.img != null">
            <span v-if="scope.row.img === null"></span>
          </template>
        </el-table-column>

        <el-table-column label="操作人" align="center" prop="createBy" />
        <el-table-column label="操作时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :title="title" v-model="creditLimitAmountOpen" width="500px" append-to-body>
      <el-form ref="merchantRef" :model="addAmountParams" :rules="rules" label-width="80px">
        <el-form-item label="金额" prop="account">
          <el-input v-model="addAmountParams.amount" placeholder="请输入金额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCreditLimitAmountForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="title" v-model="balanceAmountOpen" width="500px" append-to-body>
      <el-form ref="merchantRef" :model="addAmountParams" :rules="rules" label-width="80px">
        <el-form-item label="金额" prop="account">
          <el-input v-model="addAmountParams.amount" placeholder="请输入金额" />
        </el-form-item>

        <el-form-item label="图片" prop="img">
          <el-upload
              class="avatar-uploader"
              :action="uploadImgServer"
              accept="jpg,jpeg,png"
              :headers="{
              token: token
            }"
              :show-file-list="false"
              :before-upload="handleBeforeUpload"
              :on-success="handleUrlSuccess"
          >
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="addAmountParams.img" :src="addAmountParams.img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBalanceAmountForm">确 定</el-button>
          <el-button @click="cancelAmountForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>



  </div>
</template>

<script setup name="Merchant">
import { listMerchant, getMerchant, delMerchant, addMerchant, updateMerchant, operate, listMerchantCreditLimit,
  listMerchantBalance, listMerchantLevelInfo, submitBalanceAmount, submitCreditLimitAmount } from "@/api/business/merchant";

import { localGet, uploadImgServer, hasEmoji } from "@/api/business/goodsInfo";

const { proxy } = getCurrentInstance();
const { sys_show_hide, sys_normal_disable } = proxy.useDict("sys_show_hide", "sys_normal_disable");

const merchantList = ref([]);
const merchantCreditLimitList = ref([]);
const merchantBalanceList = ref([]);
const open = ref(false);
const merchantCreditLimitOpen = ref(false);
const merchantBalanceOpen = ref(false);
const creditLimitAmountOpen = ref(false);
const balanceAmountOpen = ref(false);
const loading = ref(true);
const merchantCreditLimitLoading = ref(true);
const merchantBalanceLoading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const router = useRouter();
const merchantLevelArr = ref([]);//品牌list

const token =  localGet('token') || '';

const isEdit = ref(false);

const data = reactive({

  uploadImgServer,
  token: localGet('token') || '',

  form: {
    merchantLevelId : null,
    merchantLevelName : null,

  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    account: null,
    phone: null
  },
  rules: {

  },

  searchParams: {
    id: null,
    menuCode: null
  },

  searchRecordParams: {
    merchantId: null,
    type: null
  },

  addAmountParams: {
    merchantId: null,
    amount: null,
    img : null
  },

});

const { queryParams, form, rules, searchParams , searchRecordParams, addAmountParams} = toRefs(data);

/** 查询商户信息列表 */
function getList() {
  loading.value = true;
  listMerchant(queryParams.value).then(response => {
    merchantList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    account: null,
    phone: null
  };
  proxy.resetForm("merchantRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  isEdit.value = false;
  title.value = "添加商户信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  isEdit.value = true;
  const id = row.id || ids.value
  getMerchant(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商户信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["merchantRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMerchant(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMerchant(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}


/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除商户数据项？').then(function() {
    return delMerchant(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/admin/merchant/export', {
    ...queryParams.value
  }, `商户_${new Date().getTime()}.xlsx`)
}

/** 操作 */
function handleOperate(row, menuCode) {
  const id = row.id;

  searchParams.value.id = id;
  searchParams.value.menuCode = menuCode;

  proxy.$modal.confirm('是否确认？').then(function() {
    return operate(searchParams.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => {});
}

/** 查询商户的信用额度记录 */
function handleCreditLimitRecord(row) {
  merchantCreditLimitOpen.value = true;

  const merchantId = row.id;
  searchRecordParams.value.merchantId = merchantId,
  merchantCreditLimitLoading.value = true;
  listMerchantCreditLimit(searchRecordParams.value).then(response => {
    merchantCreditLimitList.value = response.rows;
    total.value = response.total;
    merchantCreditLimitLoading.value = false;
  });
}

/** 查询商户的信用额度记录 */
function handleBalanceRecord(row) {
  merchantBalanceOpen.value = true;

  const merchantId = row.id;
  searchRecordParams.value.merchantId = merchantId,
  merchantBalanceLoading.value = true;
  listMerchantBalance(searchRecordParams.value).then(response => {
    merchantBalanceList.value = response.rows;
    total.value = response.total;
    merchantBalanceLoading.value = false;
  });
}

/** 查询商户信息列表 */
function getMerchantLevelList() {
  listMerchantLevelInfo().then(response => {
    merchantLevelArr.value = response.rows;
  });
}

function merchantLevelChange(name){
  for (let i = 0; i < merchantLevelArr.value.length; i++) {
    if (merchantLevelArr.value[i].name === name) {

      form.merchantLevelName = name;
      form.value.merchantLevelId = merchantLevelArr.value[i].id;
    }
  }
}


/** 信用额度新增 */
function addCreditLimit(row) {
  creditLimitAmountOpen.value = true;

  const merchantId = row.id;
  addAmountParams.value.merchantId = merchantId

}

/** 余额新增 */
function addBalance(row) {
  balanceAmountOpen.value = true;
  const merchantId = row.id;
  addAmountParams.value.merchantId = merchantId

}


/** 操作 */
function submitCreditLimitAmountForm() {

  proxy.$modal.confirm('是否确认？').then(function() {
    return submitCreditLimitAmount(addAmountParams.value);
  }).then(() => {
    creditLimitAmountOpen.value = false;
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => {});
}

/** 操作 */
function submitBalanceAmountForm() {

  proxy.$modal.confirm('是否确认？').then(function() {
    return submitBalanceAmount(addAmountParams.value);
  }).then(() => {
    balanceAmountOpen.value = false;
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => {});
}

function cancelAmountForm() {
  balanceAmountOpen.value = false;
  creditLimitAmountOpen.value = false;
  reset();
}


function handleBeforeUpload(file){
  const sufix = file.name.split('.')[1] || ''
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
    return false
  }
}
function handleUrlSuccess (val){
  addAmountParams.value.img = val.url || ''
}


getMerchantLevelList();
getList();
</script>

<style scoped>
.add {
  display: flex;
}
.add-container {
  flex: 1;
  height: 100%;
}
.avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}
.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
}
</style>